//
//  MineObjectHelper.m
//  Gaoloumi
//
//  Created by Jasper on 3/27/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

#import "MineObjectHelper.h"
#import "AVOSCloudSNS.h"
#import <AVOSCloud/AVOSCloud.h>
//#import <MBProgressHUD/MBProgressHUD.h>


@implementation MineObjectHelper


+ (void)removeCache {
    //===============清除缓存==============
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    //    NSLog(@"文件数 ：%d",[files count]);
    for (NSString *p in files) {
        NSError *error;
        NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}


+ (void)deleteAuthDataCache {
    id authData = [[AVUser currentUser] objectForKey:@"authData"];
    if (authData != nil && authData != [NSNull null]) {
        if ([authData objectForKey:AVOSCloudSNSPlatformQQ]) {
            [AVOSCloudSNS logout:AVOSCloudSNSQQ];
        } else if ([authData objectForKey:AVOSCloudSNSPlatformWeiXin]) {
            [AVOSCloudSNS logout:AVOSCloudSNSWeiXin];
        } else if ([authData objectForKey:AVOSCloudSNSPlatformWeiBo]) {
            [AVOSCloudSNS logout:AVOSCloudSNSSinaWeibo];
        }
    }
}

+ (void)logout {
    [self deleteAuthDataCache];
    [AVUser logOut];
}

+ (void)loginWith:(NSInteger)tag callback:(void(^)(BOOL success))callback {
    NSString *platform;
    AVOSCloudSNSType snsType;
    switch (tag) {
        case 100: {
            snsType = AVOSCloudSNSWeiXin;
            platform = AVOSCloudSNSPlatformWeiXin;
            break;
        }
        case 101: {
            snsType = AVOSCloudSNSQQ;
            platform = AVOSCloudSNSPlatformQQ;
            break;
        }
        case 102: {
            snsType = AVOSCloudSNSSinaWeibo;
            platform = AVOSCloudSNSPlatformWeiBo;
            break;
        }
        default: {
            snsType = AVOSCloudSNSSinaWeibo;
            platform = AVOSCloudSNSPlatformWeiBo;
            break;
        }
            
    }
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if ([self filterError:error]) {
            [self loginByAuthData:object platform:platform block:^(BOOL succeeded, NSError *error) {
                if ([self filterError:error]) {
                    callback(YES);
//                    appdeleg *delegate = (CDAppDelegate *)[UIApplication sharedApplication].delegate;
//                    [delegate toMain];
                } else {
                    callback(NO);
                }
            }];
        }
    } toPlatform:snsType];
}


+ (void)loginByAuthData:(NSDictionary *)authData platform:(NSString *)platform block:(AVBooleanResultBlock)block {
    __block NSString *username = authData[@"username"];
    __block NSString *avatar = authData[@"avatar"];
    [AVUser loginWithAuthData:authData platform:platform block:^(AVUser *user, NSError *error) {
        if (error) {
            block(NO, error);
        } else {
            
            if (![user.updatedAt isEqualToDate:user.createdAt]) { // 如果不等于就说明用户信息有过改动
//                 之前已经登录过、设置好用户名和头像了
            
                block(YES, nil);
            } else {
                if (username) {
                    [self countUserByUsername:username block:^(NSInteger number, NSError *error) {
                        if (error) {
                            block(NO, error);
                        } else {
                            if (number > 0) {
                                // 用户名重复了，给一个随机的后缀
                                username = [NSString stringWithFormat:@"%@%@",username, [[self uuid] substringToIndex:3]];
                                [self changeToUsername:username avatar:avatar user:user block:block];
                            } else {
                                [self changeToUsername:username avatar:avatar user:user block:block];
                            }
                        }
                    }];
                } else {
                    // 应该不可能出现这种情况
                    // 没有名字，只改头像
                    [self changeToUsername:nil avatar:avatar user:user block:block];
                }
            }
        }
    }];
}

+ (NSString *)uuid {
    NSString *chars = @"abcdefghijklmnopgrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    assert(chars.length == 62);
    int len = (int)chars.length;
    NSMutableString *result = [[NSMutableString alloc] init];
    for (int i = 0; i < 24; i++) {
        int p = arc4random_uniform(len);
        NSRange range = NSMakeRange(p, 1);
        [result appendString:[chars substringWithRange:range]];
    }
    return result;
}


+ (void)countUserByUsername:(NSString *)username block:(AVIntegerResultBlock)block {
    AVQuery *q = [AVUser query];
    [q whereKey:@"username" equalTo:username];
    [q countObjectsInBackgroundWithBlock:block];
}

+ (void)changeToUsername:(NSString *)username avatar:(NSString *)avatar user:(AVUser *)user block:(AVBooleanResultBlock)block{
    [self uploadAvatarWithUrl:avatar block:^(AVFile *file, NSError *error) {
        if (file) {
            [user setObject:file forKey:@"avatar"];
        }
        if (username) {
            user.username = username;
        }
        
        
        
        [user saveInBackgroundWithBlock:block];
    }];
}

+ (void)uploadAvatarWithUrl:(NSString *)url block:(AVFileResultBlock)block {
    if (!url) {
        block(nil, nil);
    } else {
        AVFile *file = [AVFile fileWithURL:url];
        [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (error) {
                block(nil, error);
            } else {
                block(file, nil);
            }
        }];
    }
}

+ (BOOL)filterError:(NSError *)error {
    if (error.code == AVOSCloudSNSErrorUserCancel) {
        [self showHUDText:@"取消了登录"];
        return NO;
    }
    if (error) {
        [AVAnalytics event:@"Alert Error" attributes:@{@"desc": error.description}];
    }
    if (error) {
         if ([error.domain isEqualToString:NSURLErrorDomain]) {
            [self alert:@"网络连接发生错误"];
        }
        else {
#ifndef DEBUG
            [self alert:[NSString stringWithFormat:@"%@", error]];
#else
            NSString *info = error.localizedDescription;
            [self alert:info ? info : [NSString stringWithFormat:@"%@", error]];
#endif
        }
        return NO;
    }
    return YES;
}

+ (void)alert:(NSString*)msg {
    UIAlertView *alertView=[[UIAlertView alloc]
                            initWithTitle:nil message:msg delegate:nil
                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
}

+ (void)toast:(NSString *)text {
    [self toast:text duration:2];
}

+ (void)toast:(NSString *)text duration:(NSTimeInterval)duration {
    [AVAnalytics event:@"toast" attributes:@{@"text": text}];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//    //    hud.labelText=text;
//    hud.detailsLabelFont = [UIFont systemFontOfSize:14];
//    hud.detailsLabelText = text;
//    hud.margin = 10.f;
//    hud.removeFromSuperViewOnHide = YES;
//    hud.mode = MBProgressHUDModeText;
//    [hud hide:YES afterDelay:duration];
}

+ (void)showHUDText:(NSString*)text{
    [self toast:text];
}


@end
